package com.ap.core.business.message.domain.translators.header.impl;

import com.ap.core.business.message.domain.translators.AbstractHeaderTranslator;
import com.ap.core.business.message.domain.translators.BindingListener;
import com.ap.core.business.message.domain.translators.BindingMetaData;
import com.ap.core.common.types.InputMessageType;
import com.ap.core.dao.BasketReferenceDao;
import com.ap.core.domain.ApMessage;
import com.ap.core.domain.BasketReference;
import com.ap.core.domain.OrderPayment;
import com.ap.core.exception.BusinessFailureException;
import com.ap.core.message.managepayment.info.RetrieveRTPMessageInfo;
import org.joda.time.LocalDate;

/**
 * User: Ranjit.Singh
 * Implementation class for {@link com.ap.core.business.message.domain.translators.Translator}
 */
public class RetrieveRTPMsgHdrTranslator extends AbstractHeaderTranslator<RetrieveRTPMessageInfo> {

    private BasketReferenceDao basketReferenceDao;


    @Override
    public void translate(RetrieveRTPMessageInfo boundObject, BindingMetaData metaData, BindingListener bindingListener) throws BusinessFailureException {
        final InputMessageType inputMessageType = metaData.getInputMessageType();
        OrderPayment originalOrderPayment = null;
        if(null != boundObject.getRequestInfo().getApTransactionId()){
            originalOrderPayment =  orderPaymentDao.getReadOnlyOrderPaymentByApTranId(boundObject.getRequestInfo().getApTransactionId());
        }else if(null != boundObject.getRequestInfo().getBRN()){
            final BasketReference basketReference = basketReferenceDao.getReadOnlyBasketReferenceByBRN(boundObject.getRequestInfo().getBRN());
            originalOrderPayment = null == basketReference ? null: orderPaymentDao.getReadOnlyOrderPaymentByApTranId(basketReference.getApTransactionId());
        }
        final String reconciliationCycleId = originalOrderPayment == null ? metaData.getReconciliationInfo().getReconciliationCycleId() : originalOrderPayment.getReconciliationCycleId();
        final LocalDate reconciliationDate =  originalOrderPayment == null ? metaData.getReconciliationInfo().getReconciliationDate() : originalOrderPayment.getReconciliationDate();
        final ApMessage apMessage = populateApEvent(inputMessageType, reconciliationCycleId,  reconciliationDate, boundObject.getMsgHdr().getMsgId(), boundObject.getMsgHdr().getMsgTimestamp(), boundObject.getRequestInfo().getFIId()) ;

        bindingListener.onApMessage(apMessage, originalOrderPayment);
    }

    public void setBasketReferenceDao(BasketReferenceDao basketReferenceDao) {
        this.basketReferenceDao = basketReferenceDao;
    }
}
